<template>
    <!-- 添加 | 修改 | 查看弹窗 -->
    <el-dialog v-if="drawerVisible" :title="`${drawerProps.title}`" v-model="drawerVisible" width="1000px" append-to-body
        center destroy-on-close draggable :close-on-click-modal='false'>
        <el-form ref="ruleFormRef" :model="drawerProps.rowData" :rules="rules" label-width="auto"
            :disabled="drawerProps.title == '查看'">
            <!-- <el-form-item label="企业名称" prop="companyName">
                <el-input v-model="drawerProps.rowData!.companyName" placeholder="请输入企业名称" />
            </el-form-item>
            <el-form-item label="谏言人" prop="adviceName">
                <el-input v-model="drawerProps.rowData!.adviceName" placeholder="请输入谏言人" />
            </el-form-item>
            <el-form-item label="谏言人职务" prop="advicePosition">
                <el-input v-model="drawerProps.rowData!.advicePosition" placeholder="请输入谏言人职务" />
            </el-form-item>
            <el-form-item label="谏言内容">
                <editor v-model="drawerProps.rowData!.content" :min-height="192" />
            </el-form-item>
            <el-form-item label="流程id" prop="processId">
                <el-input v-model="drawerProps.rowData!.processId" placeholder="请输入流程id" />
            </el-form-item>
            <el-form-item label="是否删除0否1是" prop="delFlag">
                <el-input v-model="drawerProps.rowData!.delFlag" placeholder="请输入是否删除0否1是" />
            </el-form-item> -->
            <el-button type="primary" @click="drawerProps.rowData.approvalList.push({})">增加节点</el-button>
            <div class="first-name">{{ drawerProps.firstTitle }}</div>
            <el-card style="width: 99%;margin-top: 10px;" v-for="(item, index) in drawerProps.rowData.approvalList">
                <div class="title head-title bottom-border">
                    {{ numberToChinese(index + 1) }}级审批人
                    <!-- <el-button type="danger" :icon="Delete"
                       /> -->
                    <el-icon :size="22" @click.prevent="drawerProps.rowData.approvalList.splice(index, 1)">
                        <Delete color="#F56C6C" />
                    </el-icon>
                </div>
                <el-row class="el-rows">
                    <el-col :span="8">
                        <el-form-item label="审核类型:" :prop="`approvalList.${index}.auditType`" :rules='rules.auditType'
                            style="margin-bottom: 0;">
                            <el-select v-model="item.auditType" placeholder="请选择审核类型">
                                <el-option label="自动通过" :value="0" />
                                <el-option label="人工审批" :value="1" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="角色:" :prop="`approvalList.${index}.auditRoleId`" :rules='rules.auditRoleId'
                            style="margin-bottom: 0;">
                            <MySelect v-model="item.auditRoleId" :request-api="listRole" placeholder="选择角色"
                                :fieldNames="roleFiled" :data="item" :change="(v, list) => changeRole(v, list, index)"
                                :initParam="{ pageNum: 1, pageSize: 99999 }" class="financing-list-detail-input" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="审批人:" prop="expectAuditer" style="margin-bottom: 0;">
                            <el-select v-model="item.expectAuditer" placeholder="请选择审批人" multiple collapse-tags
                                collapse-tags-tooltip :max-collapse-tags="4">
                                <el-option :label="element.userName" :value="element.userName"
                                    v-for="element in item.peopleList" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

            </el-card>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确 定</el-button>
                <el-button @click="drawerVisible = false">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template >
<script setup lang="ts" >
import { ref, reactive, getCurrentInstance, onMounted } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Delete } from "@element-plus/icons-vue";
import {
    listConfig,
    getConfig,
    delConfig,
    addConfig,
    updateConfig
} from "@/api/ApprovalConfiguration";
import { listRole } from "@/api/system/role";
import { allocatedUserList, authUserCancel, authUserCancelAll } from "@/api/system/role";
const proxy = getCurrentInstance()?.proxy;
let roleFiled = { label: "roleName", value: "roleId", labelName: "auditRole", autoLable: true };

//父组件传递参数类型
interface DiolgProps {
    title: string;
    isView: boolean;
    rowData: any;
    api?: (params: any) => Promise<any>;
    getTableList?: () => void;
    [proName: string]: any
}
// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const drawerVisible = ref(false);
function numberToChinese(num) {
    const chineseNumbers = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
    const units = ['', '十', '百', '千', '万', '亿'];

    if (num === 0) {
        return chineseNumbers[0];
    }

    let chineseStr = '';
    let unitPos = 0;
    let zero = false;

    while (num > 0) {
        const digit = num % 10;
        if (digit === 0) {
            if (!zero) {
                chineseStr = chineseNumbers[0] + chineseStr;
                zero = true;
            }
        } else {
            chineseStr = chineseNumbers[digit] + units[unitPos] + chineseStr;
            zero = false;
        }
        num = Math.floor(num / 10);
        unitPos++;
    }

    // 处理特殊情况，如 "一十" 应为 "十"
    if (chineseStr[0] === chineseNumbers[0]) {
        chineseStr = chineseStr.slice(1);
    }

    return chineseStr;
}
const drawerProps = ref<DiolgProps>({
    isView: false,
    title: "",
    rowData: {
        approvalList: []
    },
    module: ""
});
const changeRole = async (v, list, index) => {
    console.log(v, list)
    if (v) {
        let { rows } = await allocatedUserList({ roleId: v, pageNum: 1, pageSize: 9999 });
        drawerProps.value.rowData.approvalList[index].peopleList = rows;
        drawerProps.value.rowData.approvalList[index].expectAuditer = undefined
    } else {
        //清空掉对应的审批人员数组
        drawerProps.value.rowData.approvalList[index].peopleList = [];
        drawerProps.value.rowData.approvalList[index].expectAuditer = undefined
    }
}
// 接收父组件传过来的参数
const acceptParams = async (params: DiolgProps) => {
    drawerProps.value = params;
    console.log("params", params)
    let { rows } = await listConfig({ module: params.module });

    if (rows.length > 0) {
        console.log("根据每一个roleid 去调用")
        //根据auditRoleId 去获取对应节点下的审批人数据
        for (const item of rows) {
            if (item.expectAuditer == '') {
                item.expectAuditer = undefined
            }else{
                item.expectAuditer = item.expectAuditer.split(',');
            }
            // item.expectAuditer =  ? undefined : item.expectAuditer.split(',');
            let { rows: userList } = await allocatedUserList({ roleId: item.auditRoleId, pageNum: 1, pageSize: 9999 });
            item.peopleList = userList ?? [];
        }
    }
    drawerProps.value.rowData.approvalList = rows;
    proxy?.$forceUpdate();
    drawerVisible.value = true;
};

const handleSubmit = () => {
    ruleFormRef.value!.validate(async valid => {
        if (!valid) return;
        try {
            drawerProps.value.rowData.approvalList = drawerProps.value.rowData.approvalList.map((item, index) => {
                let expectAuditerValue;

                // 检查 expectAuditer 是否为数组
                if (Array.isArray(item.expectAuditer)) {
                    // 如果是数组，则使用 join 方法转换为逗号分隔的字符串
                    expectAuditerValue = item.expectAuditer.join(',');
                } else {
                    // 如果不是数组（即已经是字符串），则直接使用
                    expectAuditerValue = item.expectAuditer;
                }

                return {
                    ...item,
                    step: index + 1,
                    expectAuditer: expectAuditerValue
                };
            });
            await updateConfig({ module: drawerProps.value.module, 'shBaseProcessConfigs': drawerProps.value.rowData.approvalList });
            ElMessage.success({ message: `${drawerProps.value.title}成功！` });
            drawerProps.value.getTableList!();
            drawerVisible.value = false;
        } catch (error) {
            console.log(error);
        }
    });
};

const rules = reactive(
    {
        adviceName: [
            { required: true, message: '谏言人不能为空', trigger: 'blur' }
        ],
        advicePosition: [
            { required: true, message: '谏言人职务不能为空', trigger: 'blur' }
        ],
        content: [
            { required: true, message: '谏言内容不能为空', trigger: 'blur' }
        ],
        processId: [
            { required: true, message: '流程id不能为空', trigger: 'blur' }
        ],
        delFlag: [
            { required: true, message: '是否删除0否1是不能为空', trigger: 'blur' }
        ],
        auditType: [
            { required: true, message: '请选择审核类型', trigger: 'blur' }
        ],
        auditRoleId: [
            { required: true, message: '请选择审核角色', trigger: 'blur' }
        ]
    }
);
defineExpose({
    acceptParams
});
</script>
<style scoped lang="scss">
.first-name {
    font-size: 18px;
    font-weight: bold;
    margin: 7px 0;
}
</style>